package com.hb.znpt.utils;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.unitlib.base.utils.SPUtils;

import java.io.File;

public class OssManager {

    private static final String TAG = "OssManager";

    // 访问的endpoint地址
    private static final String OSS_ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";

    private static final String BUCKET_NAME = "znxt";

    public static final String POINT = "http://znxt.oss-cn-beijing.aliyuncs.com";

    private OSS oss = null;

    private Context context;

    private OSSCredentialProvider credentialProvider;

    private static volatile OssManager ossUtils;

    public OssManager() {

    }

    public static OssManager getInstance() {
        if (ossUtils == null) {
            synchronized (OssManager.class) {
                if (ossUtils == null) {
                    ossUtils = new OssManager();
                }
            }
        }
        return ossUtils;
    }

    /**
     * 初始化
     **/
    public void init(Context context, String accessKeyId, String accessKeySecret, String token) {
        this.context = context;
        try {
            credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, token);

            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(30 * 1000); // 连接超时， 默认15秒
            conf.setSocketTimeout(30 * 1000);     // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5);      // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(3);             // 失败后最大重试次数，默认2次

            OSSClient ossClient = new OSSClient(context, OSS_ENDPOINT, credentialProvider, conf);
            oss = ossClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.e(TAG, "初始化完毕");
        OSSLog.enableLog();
    }

    /**
     * 初始化
     **/
    public void init(Context context) {
        this.context = context;
        try {
            credentialProvider = new STSGetter();
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(60 * 1000); // 连接超时， 默认15秒
            conf.setSocketTimeout(60 * 1000);     // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5);      // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2);             // 失败后最大重试次数，默认2次
            oss = new OSSClient(context, OSS_ENDPOINT, credentialProvider, conf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.e(TAG, "初始化完毕");
        OSSLog.enableLog();
    }

    /**
     * 普通上传，比如image
     **/
    public void upload(String filePath, OSSCompletedCallback callback) {
        String path = "app/" + SPUtils.getInstance().getString(Constants.SP_USERCARD) + "/";
        String name = new File(filePath).getName();
        LogUtils.e(TAG, "name：" + path + name + " filePath:" + filePath);
        // 指定数据类型，没有指定会自动根据后缀名判断
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentType("image/jpeg");
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BUCKET_NAME, path + name, filePath);
        put.setMetadata(objectMeta);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                int progress = (int) (100 * currentSize / totalSize);
                LogUtils.e(TAG, "上传进度：" + progress);
            }
        });
        OSSAsyncTask<PutObjectResult> task = oss.asyncPutObject(put, callback);
    }
}
